//
//  TimeRoomViewController.m
//  QRMaster
//
//  Created by myApple on 15/7/25.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "TimeRoomViewController.h"
#import "AllocateRoomModel.h"
#import "staffRoomTimeCell.h"
#import "TouchBtnColor.h"
#import "PromptInfoView.h"
#import "RequestNetWork.h"
#import "Reachability.h"
#import "setTimeModel.h"
#import "staffTimeCell.h"
#import "AllocateRoomModel.h"
#import "StaffTimeChooseView.h"
#import "AssignStaffRoomTimeCell.h"

@interface TimeRoomViewController ()<UITableViewDataSource,UITableViewDelegate,StaffTimeChooseViewDelegate,UIGestureRecognizerDelegate>
{
    UITableView * roomTableView;
    NSMutableArray * roomDataArray;
    UIView * backView;
    
    BOOL isSign;//单选还是多选状态
    
    UILabel * bottomLabel;//底部选择按钮
    UILabel * bottomSelectTimeLabel;//底部选择时间按钮
    
    NSString * timeIdString;//时间段的时间字符串
    NSMutableArray * selectRoomId;//选择的roomid号;
    NSMutableArray * selectTimeInfo;//选中的时间段信息
    
    UIImageView * submitImageView;
    UILabel * submitLabel;
    UIButton * backBtn;
    UIImageView * buttomRightImgView;
    StaffTimeChooseView * staffTimeView;
    
    UITableView * timeTableView;
    NSMutableArray * timeArray;
    NSIndexPath * beforeIndexPath;//记住之前的cell 单选时需要取消
    
    NSArray * weekData;
    
    BOOL clickSureFlag;//是否提交成功（提交成功要把其他选中数据变成0）

}

@end

@implementation TimeRoomViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        roomDataArray = [[NSMutableArray alloc]init];
        timeArray = [[NSMutableArray alloc]init];
        selectRoomId = [[NSMutableArray alloc]init];
        selectTimeInfo = [[NSMutableArray alloc]init];
        clickSureFlag = NO;
        isSign = YES;//默认单选
        weekData = @[NSLocalizedString(@"Sunday", nil),NSLocalizedString(@"Monday", nil),NSLocalizedString(@"Tuesday", nil),NSLocalizedString(@"Wednesday", nil),NSLocalizedString(@"Thursday", nil),NSLocalizedString(@"Friday", nil),NSLocalizedString(@"Saturday", nil)];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    self.title = NSLocalizedString(@"setTime", nil);
    [self prepareTableView];
    [self prepareNavBtn];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self prepareBottomView];
    [self prepareTimeView];
    submitImageView.hidden = NO;
    backBtn.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    submitImageView.hidden = YES;
    backBtn.hidden = YES;
}

-(void)setStaffTimeRoomArray:(NSArray *)staffTimeRoomArray
{
    _staffTimeRoomArray = staffTimeRoomArray;
    roomDataArray = [NSMutableArray arrayWithArray:_staffTimeRoomArray];
}

-(void)setManagerTimeArray:(NSMutableArray *)managerTimeArray
{
    _managerTimeArray = managerTimeArray;
    [timeTableView reloadData];
}

-(void)prepareNavBtn
{
    submitImageView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH - 66, 2, 50, 40)];
    submitImageView.userInteractionEnabled = NO;
    UITapGestureRecognizer * submitTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(makeSure)];
    [submitImageView addGestureRecognizer:submitTap];
    [self.navigationController.navigationBar addSubview:submitImageView];
    
    submitLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 50, 20)];
    submitLabel.text = NSLocalizedString(@"authenSubmit",@"完成");
    submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    submitLabel.font = [UIFont systemFontOfSize:15.0];
    submitLabel.textAlignment = NSTextAlignmentRight;
    [submitImageView addSubview:submitLabel];
    
    float x = 0;
    float y = 0;
    float width = 56;
    float height = 40;
    backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(x, y, width, height);
    [backBtn addTarget:self action:@selector(userBack) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:backBtn];
}

-(void)prepareTableView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = UI_SCREEN_HEIGHT;
    float x = 0;
    float y = 5;
    float width = ScreenWidth;
    float height = ScreenHeight - 64 - y - 44;
    
    roomTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    roomTableView.dataSource = self;
    roomTableView.delegate = self;
    roomTableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:roomTableView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return roomDataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AssignRoomTimeModel * model = roomDataArray[indexPath.row];
    AssignStaffRoomTimeCell * cell = [AssignStaffRoomTimeCell cellWithTableView:tableView];
    cell.allTimeArray = _managerTimeArray;
    cell.accessoryType = UITableViewCellAccessoryNone;
    [cell setData:model];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    AssignRoomTimeModel * model = roomDataArray[indexPath.row];
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!isSign) {
        if (cell.accessoryType == UITableViewCellAccessoryCheckmark ) {
            cell.accessoryType = UITableViewCellAccessoryNone;
            [selectRoomId removeObject:model.roomId];
        }
        else
        {
            [selectRoomId addObject:model.roomId];
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
    }
    else
    {
        [selectRoomId removeAllObjects];
        if (beforeIndexPath.row == indexPath.row) {
           //如果点击同一个
            if (cell.accessoryType == UITableViewCellAccessoryNone) {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
                [selectRoomId addObject:model.roomId];
            }
            else
            {
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
        }
        else
        {
            UITableViewCell * beforeCell = [tableView cellForRowAtIndexPath:beforeIndexPath];
            beforeCell.accessoryType = UITableViewCellAccessoryNone;
            [selectRoomId addObject:model.roomId];
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        if (selectRoomId.count > 0) {
            backView.hidden = NO;
        }
    }
    [self judgeSelect];
    beforeIndexPath = indexPath;
}

#pragma mark ----------底部view及其操作
-(void)prepareBottomView
{
    float x = 0;
    float y = UI_SCREEN_HEIGHT - 44 - 64;
    float width = UI_SCREEN_WIDTH;
    float height = 44;
    UIView * buttomView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    buttomView.backgroundColor = UIColorFromRGB(0xf5f5f5);
    [self.view addSubview:buttomView];
    
    y = 0;
    width = 80;
    height = 44;
    UIImageView * bottomLeftImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    bottomLeftImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer * leftTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttomLeftClick)];
    [bottomLeftImgView addGestureRecognizer:leftTap];
    [buttomView addSubview:bottomLeftImgView];
    
    x = 16;
    y = 12;
    width = 60;
    height = 20;
    bottomLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    bottomLabel.font = [UIFont systemFontOfSize:14.0];
    bottomLabel.text = @"选择";
    [bottomLeftImgView addSubview:bottomLabel];
    
    x = UI_SCREEN_WIDTH/ 2.0;
    width = x;
    height = 44;
    y = 0;
    buttomRightImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    buttomRightImgView.userInteractionEnabled = YES;
    buttomRightImgView.hidden = YES;
    UITapGestureRecognizer * rightTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttomRightClick)];
    [buttomRightImgView addGestureRecognizer:rightTap];
    [buttomView addSubview:buttomRightImgView];
    
    x = 0;
    y = 12;
    width = UI_SCREEN_WIDTH / 2.0 - 16.0;
    height = 20;
    bottomSelectTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    bottomSelectTimeLabel.text = @"分配开门周期";
    bottomSelectTimeLabel.font = [UIFont systemFontOfSize:14.0];
    bottomSelectTimeLabel.textAlignment = NSTextAlignmentRight;
    bottomSelectTimeLabel.textColor = UIColorFromRGB(0x00aff0);
    [buttomRightImgView addSubview:bottomSelectTimeLabel];
    
}

-(void)buttomLeftClick
{
    buttomRightImgView.hidden = !buttomRightImgView.hidden;
    if (buttomRightImgView.hidden) {
        bottomLabel.text = @"选择";
        isSign = YES;
        [selectRoomId removeAllObjects];
        [roomTableView reloadData];
        [self judgeSelect];
    }
    else
    {
        bottomLabel.text = @"取消";
        isSign = NO;
    }
}

-(void)buttomRightClick
{
    if (backView.hidden) {
        backView.hidden = NO;
    }
}


-(void)prepareTimeView
{
    float x = 0;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = UI_SCREEN_HEIGHT;
    backView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    backView.backgroundColor = [UIColor clearColor];
    backView.hidden = YES;

    UITapGestureRecognizer * cancelTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelTimeView)];
    cancelTap.delegate = self;
    [backView addGestureRecognizer:cancelTap];
    [self.view addSubview:backView];
    
    y = UI_SCREEN_HEIGHT - _managerTimeArray.count * 56 - 64 - 0.5;
    height = _managerTimeArray.count * 56 + 0.5;
    staffTimeView = [[StaffTimeChooseView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    staffTimeView.totalTimeArray = _managerTimeArray;
    staffTimeView.delegate = self;
    [backView addSubview:staffTimeView];
    
}

-(void)cancelTimeView
{
    backView.hidden = YES;
}

#pragma mark -- 解决tableview中手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

#pragma mark ----------- 时间选择的代理方法
-(void)selectTimeId:(NSString *)timeId
{
    timeIdString = timeId;
    [self judgeSelect];
}

-(void)selectTime:(UIButton *)btn
{
    [btn setBackgroundColor:RGBA(152, 194, 52, 1)];
}

-(void)makeSure
{
    if (selectRoomId.count < 1) {
        [PromptInfoView showMessage:NSLocalizedString(@"chooseRoomPlease", nil) superView:self.view];
        return;
    }
    
    if ([self IsHaveNetwork]) {
        return;
    }
    NSMutableString * roomIdString = [[NSMutableString alloc]init];
    for (NSString * selectRoomid in selectRoomId) {
        [roomIdString appendString:selectRoomid];
        [roomIdString appendString:@","];
    }
    [roomIdString substringToIndex:[roomIdString length]-2];
    @try {
        NSRange roomRange;
        roomRange.location = roomIdString.length - 1;
        roomRange.length = 1;
        [roomIdString deleteCharactersInRange:roomRange];
    }
    @catch (NSException *exception) {
        return;
    }
    
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    [postDict setValue:_staffId forKey:@"userId"];
    [postDict setValue:timeIdString == nil?@"":timeIdString forKey:@"timeIds"];
    [postDict setValue:roomIdString forKey:@"roomIds"];
    [self startWaiting:nil color:nil addToView:self.view];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(EDITSTAFFROOMTIME) params:postDict block:^(id downLoadData, id error){
        [self stopWaiting];
        id data = [downLoadData objectForKey:@"data"];
        if (data)
        {
            backView.hidden = YES;
            [PromptInfoView showMessage:NSLocalizedString(@"addTimeSuccess", nil) superView:self.view];
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
       
    }];
    
}

#pragma mark ----------用户自定义返回键
-(void)userBack
{
    if ([self judgeSelect]) {
        UIAlertView * alterView = [[UIAlertView alloc]initWithTitle:nil message:NSLocalizedString(@"shouldSave", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"notSave", nil) otherButtonTitles:NSLocalizedString(@"save", nil), nil];
        [alterView show];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self makeSure];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(BOOL)judgeSelect
{
    if (selectRoomId.count > 0 ) {
        submitImageView.userInteractionEnabled = YES;
        submitLabel.textColor = UIColorFromRGB(0x7dc234);
        return YES;
    }
    else
    {
        submitImageView.userInteractionEnabled = NO;
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
        return NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
